package com.le.tester.imooc.oldfairy;

import com.le.tester.javaThink.fifth.chapter14_StreamingProgramming.ForEach;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * createTime：2023/8/28 10:01
 * description：Lucene 全文搜索
 */
public class LuceneCN {

    private static final String INDEX_DIR = "E:\\L.Info\\devToolData\\LuceneData\\index";

    private IndexWriter createWrite() throws IOException {
        Path path = Paths.get(INDEX_DIR);
        FSDirectory open = FSDirectory.open(path);

        //analyzer-->解析成Lucene
        StandardAnalyzer standardAnalyzer = new StandardAnalyzer();
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(standardAnalyzer);

        return new IndexWriter(open, indexWriterConfig);
    }

    private IndexSearcher createSearcher() throws IOException {
        Path path = Paths.get(INDEX_DIR);
        FSDirectory open = FSDirectory.open(path);
        DirectoryReader reader = DirectoryReader.open(open);
        return new IndexSearcher(reader);
    }

    @Test
    public void testIndexWrite() throws IOException {
        IndexWriter write = this.createWrite();
        Document doc = new Document();
        doc.add(new TextField("content", "Today ... lucene", Field.Store.YES));


        write.addDocument(doc);
        write.flush();
        write.close();

    }

    @Test
    public void testQuery() throws ParseException, IOException {
        Query query = new QueryParser("content", new StandardAnalyzer())
                .parse("lucene");

        IndexSearcher searcher = this.createSearcher();

        //命中前十条
        TopDocs topDocs = searcher.search(query, 10);

        for (ScoreDoc sdItem : topDocs.scoreDocs) {
            int docId = sdItem.doc;
            Document doc = searcher.doc(docId);
            System.out.println(sdItem.score);
        }

    }


}
